﻿namespace WMS6.SQLServerDAL
{
    using System;
    using System.Collections.Generic;
    using System.Data;
    using System.Data.Common;
    using System.Data.SqlClient;
    using System.Text;
    using WMS6.Common;
    using WMS6.DataEntity;
    using WMS6.DBUtility;
    using WMS6.IDAL;
    using WMS6.QueryEntity;

    public class UserBillingentityDA : IUserBillingentityDA
    {
        private string BILLINGENTITY_ID = "@BILLINGENTITY_ID";
        private string CREATED_BY = "@CREATED_BY";
        private string IS_DEFAULT = "@IS_DEFAULT";
        private string SQL_CHECK_USER_BILLINGENTITY_ID_UNIQUE = " SELECT COUNT(1) FROM @_@USER_BILLINGENTITY WHERE USER_ID = @USER_ID AND BILLINGENTITY_ID = @BILLINGENTITY_ID ";
        private string SQL_DELETE_USER_BILLINGENTITY = " DELETE FROM @_@USER_BILLINGENTITY WHERE USER_ID = @USER_ID ";
        private string SQL_INSERT_USER_BILLINGENTITY = " INSERT INTO @_@USER_BILLINGENTITY ( USER_ID, BILLINGENTITY_ID, IS_DEFAULT, CREATED_BY, CREATED_DATE, UPDATED_BY, UPDATED_DATE) VALUES ( @USER_ID, @BILLINGENTITY_ID, @IS_DEFAULT, @CREATED_BY, GETDATE(), @UPDATED_BY, GETDATE() )  ";
        private string SQL_SELECT_ALL_USER_BILLINGENTITY = " SELECT  ROWID, USER_ID, BILLINGENTITY_ID, IS_DEFAULT, TS, CREATED_BY, CREATED_DATE, UPDATED_BY, UPDATED_DATE  FROM  @_@USER_BILLINGENTITY ";
        private string SQL_UPDATE_USER_BILLINGENTITY = " UPDATE @_@USER_BILLINGENTITY SET IS_DEFAULT = @IS_DEFAULT, UPDATED_BY = @UPDATED_BY, UPDATED_DATE = GETDATE() WHERE USER_ID = @USER_ID AND BILLINGENTITY_ID = @BILLINGENTITY_ID  ";
        private string TS = "@TS";
        private string UPDATED_BY = "@UPDATED_BY";
        private string USER_ID = "@USER_ID";

        public bool CheckUserBillingentityIDUnique(string userID, string BillingentityID, string whLoginID)
        {
            SqlParameter[] paras = new SqlParameter[] { new SqlParameter("@USER_ID", userID), new SqlParameter("@BILLINGENTITY_ID", BillingentityID) };
            return (DBHelper.ExecuteScalar(CommandType.Text, this.SQL_CHECK_USER_BILLINGENTITY_ID_UNIQUE.Replace("@_@", whLoginID), paras).ToString() == "1");
        }

        public bool CheckUserBillingentityIDUnique(DataBase dataBase, DbTransaction tran, string userID, string BillingentityID, string whLoginID)
        {
            SqlParameter[] paras = new SqlParameter[] { new SqlParameter("@USER_ID", userID), new SqlParameter("@BILLINGENTITY_ID", BillingentityID) };
            return (dataBase.ExecuteScalar(tran, CommandType.Text, this.SQL_CHECK_USER_BILLINGENTITY_ID_UNIQUE.Replace("@_@", whLoginID), paras).ToString() == "1");
        }

        public int DeleteUserBillingentity(string userID, string BillingentityID, string whLoginID)
        {
            string strSql = this.SQL_DELETE_USER_BILLINGENTITY.Replace("@_@", whLoginID) + "AND BILLINGENTITY_ID = @BILLINGENTITY_ID ";
            int result = 0;
            DataBase dataBase = new DataBase();
            DbConnection conn = dataBase.connection;
            conn.Open();
            DbTransaction tran = conn.BeginTransaction();
            try
            {
                SqlParameter[] paras = new SqlParameter[] { new SqlParameter("@USER_ID", userID), new SqlParameter("@BILLINGENTITY_ID", BillingentityID) };
                result += dataBase.ExecuteNonQuery(tran, CommandType.Text, strSql, paras);
                tran.Commit();
            }
            catch (SqlException sqlEx)
            {
                tran.Rollback();
                CommonErrorHandler.ErrorHandler(sqlEx, LogType.Error);
            }
            finally
            {
                conn.Close();
            }
            return result;
        }

        public int DeleteUserBillingentity(DataBase dataBase, DbTransaction tran, string userID, string whLoginID)
        {
            int result = 0;
            try
            {
                SqlParameter[] paras = new SqlParameter[] { new SqlParameter("@USER_ID", userID) };
                result += dataBase.ExecuteNonQuery(tran, CommandType.Text, this.SQL_DELETE_USER_BILLINGENTITY.Replace("@_@", whLoginID), paras);
            }
            catch (SqlException sqlEx)
            {
                CommonErrorHandler.ErrorHandler(sqlEx, LogType.Error);
            }
            return result;
        }

        public int DeleteUserBillingentity(DataBase dataBase, DbTransaction tran, string userID, string BillingentityID, string whLoginID)
        {
            string strSql = this.SQL_DELETE_USER_BILLINGENTITY.Replace("@_@", whLoginID) + "AND BILLINGENTITY_ID = @BILLINGENTITY_ID ";
            int result = 0;
            try
            {
                SqlParameter[] paras = new SqlParameter[] { new SqlParameter("@USER_ID", userID), new SqlParameter("@BILLINGENTITY_ID", BillingentityID) };
                result += dataBase.ExecuteNonQuery(tran, CommandType.Text, strSql, paras);
            }
            catch (SqlException sqlEx)
            {
                CommonErrorHandler.ErrorHandler(sqlEx, LogType.Error);
            }
            return result;
        }

        public int DeleteUserBillingentityByBillingentityID(DataBase dataBase, DbTransaction tran, string billingentityID, string whLoginID)
        {
            int result = 0;
            try
            {
                string StrSql = " DELETE FROM SYSADM.USER_BILLINGENTITY WHERE BILLINGENTITY_ID = '" + billingentityID + "'";
                result += dataBase.ExecuteNonQuery(tran, CommandType.Text, StrSql);
            }
            catch (SqlException sqlEx)
            {
                CommonErrorHandler.ErrorHandler(sqlEx, LogType.Error);
            }
            return result;
        }

        public DataSet GetAllUserBillingentity(string whLoginID)
        {
            string sql = this.SQL_SELECT_ALL_USER_BILLINGENTITY.Replace("@_@", whLoginID);
            return DBHelper.ExecuteDataSet(CommandType.Text, sql);
        }

        public DataSet GetAllUserBillingentity(DataBase dataBase, DbTransaction tran, string whLoginID)
        {
            string sql = this.SQL_SELECT_ALL_USER_BILLINGENTITY.Replace("@_@", whLoginID);
            return dataBase.ExecuteDataSet(tran, CommandType.Text, sql);
        }

        public DataSet GetAuthorizationUserByBillingentityID(string billingentityID, string whLoginID)
        {
            StringBuilder StrSql = new StringBuilder();
            StrSql.AppendFormat("SELECT UM.USER_ID,UM.USER_NAME, CASE LEN(ISNULL(UB.USER_ID,''))  WHEN 0 THEN 'N' ELSE 'Y' END AS PREMISSION_USER FROM SYSADM.USER_MST UM LEFT JOIN SYSADM.USER_BILLINGENTITY UB ON UM.USER_ID = UB.USER_ID AND UB.BILLINGENTITY_ID = '{0}'", billingentityID);
            return DBHelper.ExecuteDataSet(CommandType.Text, StrSql.ToString());
        }

        public List<UserBillingentityInfo> GetAuthorizedBillingentityByUserID(string userID, string whLoginID)
        {
            List<UserBillingentityInfo> UserBillingentityList = new List<UserBillingentityInfo>();
            StringBuilder StrSql = new StringBuilder();
            StrSql.AppendFormat("SELECT  BE.BILLING_ENTITY_ID,BE.COMPANY,UB.IS_DEFAULT FROM {1}BILLING_ENTITY BE  INNER JOIN  SYSADM.USER_BILLINGENTITY UB ON BE.BILLING_ENTITY_ID = UB.BILLINGENTITY_ID WHERE UB.USER_ID='{0}'", userID, whLoginID);
            using (IDataReader reader = DBHelper.ExecuteReader(CommandType.Text, StrSql.ToString()))
            {
                UserBillingentityInfo userBillingentityInfo = null;
                while (reader.Read())
                {
                    userBillingentityInfo = new UserBillingentityInfo(reader["BILLING_ENTITY_ID"].ToString(), reader["COMPANY"].ToString(), reader["IS_DEFAULT"].ToString());
                    UserBillingentityList.Add(userBillingentityInfo);
                }
            }
            return UserBillingentityList;
        }

        public UserBillingentityInfo GetBillingentityByUserID(string userID)
        {
            StringBuilder StrSql = new StringBuilder();
            StrSql.AppendFormat("SELECT BILLINGENTITY_ID,IS_DEFAULT FROM SYSADM.USER_BILLINGENTITY WHERE IS_DEFAULT='Y' AND USER_ID='{0}'", userID);
            UserBillingentityInfo userBillingentityInfo = null;
            using (IDataReader reader = DBHelper.ExecuteReader(CommandType.Text, StrSql.ToString()))
            {
                while (reader.Read())
                {
                    userBillingentityInfo = new UserBillingentityInfo(reader["BILLINGENTITY_ID"].ToString(), "", reader["IS_DEFAULT"].ToString());
                }
            }
            return userBillingentityInfo;
        }

        public List<UserBillingentityInfo> GetUnauthorizedBillingentityByUserID(string userID, string whLoginID)
        {
            List<UserBillingentityInfo> userBillingentityList = new List<UserBillingentityInfo>();
            StringBuilder StrSql = new StringBuilder();
            StrSql.AppendFormat("   SELECT  BE.BILLING_ENTITY_ID,BE.COMPANY, ''AS IS_DEFAULT  FROM {1}BILLING_ENTITY BE  WHERE BE.BILLING_ENTITY_ID NOT IN( SELECT BILLINGENTITY_ID FROM SYSADM.USER_BILLINGENTITY WHERE USER_ID='{0}')", userID, whLoginID);
            using (IDataReader reader = DBHelper.ExecuteReader(CommandType.Text, StrSql.ToString()))
            {
                UserBillingentityInfo userBillingentityInfo = null;
                while (reader.Read())
                {
                    userBillingentityInfo = new UserBillingentityInfo(reader["BILLING_ENTITY_ID"].ToString(), reader["COMPANY"].ToString(), reader["IS_DEFAULT"].ToString());
                    userBillingentityList.Add(userBillingentityInfo);
                }
            }
            return userBillingentityList;
        }

        public UserBillingentityInfo GetUserBillingentityByID(string userID, string billingentityID, string whLoginID)
        {
            string sql = this.SQL_SELECT_ALL_USER_BILLINGENTITY.Replace("@_@", whLoginID) + " WHERE USER_ID = @USER_ID AND BILLINGENTITY_ID = @BILLINGENTITY_ID  ";
            SqlParameter[] paras = new SqlParameter[] { new SqlParameter("@USER_ID", userID), new SqlParameter("@BILLINGENTITY_ID", billingentityID) };
            UserBillingentityInfo userBillingentityInfo = null;
            using (IDataReader reader = DBHelper.ExecuteReader(CommandType.Text, sql, paras))
            {
                if (reader.Read())
                {
                    userBillingentityInfo = new UserBillingentityInfo((reader["ROWID"].ToString() != "") ? int.Parse(reader["ROWID"].ToString()) : 0, reader["USER_ID"].ToString(), reader["BILLINGENTITY_ID"].ToString(), reader["IS_DEFAULT"].ToString(), (byte[]) reader["TS"], reader["CREATED_BY"].ToString(), (reader["CREATED_DATE"].ToString() != "") ? DateTime.Parse(reader["CREATED_DATE"].ToString()) : new DateTime(), reader["UPDATED_BY"].ToString(), (reader["UPDATED_DATE"].ToString() != "") ? DateTime.Parse(reader["UPDATED_DATE"].ToString()) : new DateTime());
                }
            }
            return userBillingentityInfo;
        }

        public UserBillingentityInfo GetUserBillingentityByID(DataBase dataBase, DbTransaction tran, string userID, string billingentityID, string whLoginID)
        {
            string sql = this.SQL_SELECT_ALL_USER_BILLINGENTITY.Replace("@_@", whLoginID) + " WHERE USER_ID = @USER_ID AND BILLINGENTITY_ID = @BILLINGENTITY_ID  ";
            SqlParameter[] paras = new SqlParameter[] { new SqlParameter("@USER_ID", userID), new SqlParameter("@BILLINGENTITY_ID", billingentityID) };
            UserBillingentityInfo userBillingentityInfo = null;
            IDataReader reader = dataBase.ExecuteReader(tran, CommandType.Text, sql, paras);
            if (reader.Read())
            {
                userBillingentityInfo = new UserBillingentityInfo((reader["ROWID"].ToString() != "") ? int.Parse(reader["ROWID"].ToString()) : 0, reader["USER_ID"].ToString(), reader["BILLINGENTITY_ID"].ToString(), reader["IS_DEFAULT"].ToString(), (byte[]) reader["TS"], reader["CREATED_BY"].ToString(), (reader["CREATED_DATE"].ToString() != "") ? DateTime.Parse(reader["CREATED_DATE"].ToString()) : new DateTime(), reader["UPDATED_BY"].ToString(), (reader["UPDATED_DATE"].ToString() != "") ? DateTime.Parse(reader["UPDATED_DATE"].ToString()) : new DateTime());
            }
            if (!reader.IsClosed)
            {
                reader.Close();
            }
            return userBillingentityInfo;
        }

        public DataSet GetUserBillingentityByQueryList(List<string> sqlWhere, UserBillingentityQueryEntity uservendorQuery, string whLoginID)
        {
            string temp = this.SQL_SELECT_ALL_USER_BILLINGENTITY.Replace("@_@", whLoginID);
            for (int i = 0; i < sqlWhere.Count; i++)
            {
                if (i == 0)
                {
                    temp = temp + " WHERE " + sqlWhere[i].ToString();
                }
                else
                {
                    temp = temp + " AND " + sqlWhere[i].ToString();
                }
            }
            if (!uservendorQuery.IsGetAll)
            {
                temp = PagingHelper.GetPagingSQL(temp, uservendorQuery.CurrentPage, uservendorQuery.PageSize, uservendorQuery.SortField, uservendorQuery.SortDirection);
            }
            return DBHelper.ExecuteDataSet(CommandType.Text, temp);
        }

        public DataSet GetUserBillingentityByQueryList(DataBase dataBase, DbTransaction tran, List<string> sqlWhere, UserBillingentityQueryEntity uservendorQuery, string whLoginID)
        {
            string temp = this.SQL_SELECT_ALL_USER_BILLINGENTITY.Replace("@_@", whLoginID);
            for (int i = 0; i < sqlWhere.Count; i++)
            {
                if (i == 0)
                {
                    temp = temp + " WHERE " + sqlWhere[i].ToString();
                }
                else
                {
                    temp = temp + " AND " + sqlWhere[i].ToString();
                }
            }
            temp = PagingHelper.GetPagingSQL(temp, uservendorQuery.CurrentPage, uservendorQuery.PageSize, uservendorQuery.SortField, uservendorQuery.SortDirection);
            return dataBase.ExecuteDataSet(tran, CommandType.Text, temp);
        }

        public List<UserBillingentityInfo> GetUserBillingentityInfoByBillingentityIDandUserID(string billingentityID, string whLoginID)
        {
            StringBuilder StrSql = new StringBuilder();
            string sql = this.SQL_SELECT_ALL_USER_BILLINGENTITY.Replace("@_@", whLoginID) + "WHERE BILLINGENTITY_ID = '{0}'";
            StrSql.AppendFormat(sql, billingentityID);
            List<UserBillingentityInfo> userBillingentityListInfo = new List<UserBillingentityInfo>();
            using (IDataReader reader = DBHelper.ExecuteReader(CommandType.Text, StrSql.ToString()))
            {
                UserBillingentityInfo userBillingentityInfo = null;
                while (reader.Read())
                {
                    DateTime CS00001;
                    userBillingentityInfo = new UserBillingentityInfo((reader["ROWID"].ToString() != "") ? int.Parse(reader["ROWID"].ToString()) : 0, reader["USER_ID"].ToString(), reader["BILLINGENTITY_ID"].ToString(), reader["IS_DEFAULT"].ToString(), (byte[]) reader["TS"], reader["CREATED_BY"].ToString(), (reader["CREATED_DATE"].ToString() != "") ? DateTime.Parse(reader["CREATED_DATE"].ToString()) : (CS00001 = new DateTime()), reader["UPDATED_BY"].ToString(), (reader["UPDATED_DATE"].ToString() != "") ? DateTime.Parse(reader["UPDATED_DATE"].ToString()) : (CS00001 = new DateTime()));
                    userBillingentityListInfo.Add(userBillingentityInfo);
                }
            }
            return userBillingentityListInfo;
        }

        public List<UserBillingentityInfo> GetUserBillingentityInfoByBillingentityIDandUserID(DataBase dataBase, DbTransaction tran, string billingentityID, string whLoginID)
        {
            StringBuilder StrSql = new StringBuilder();
            string sql = this.SQL_SELECT_ALL_USER_BILLINGENTITY.Replace("@_@", whLoginID) + "WHERE BILLINGENTITY_ID = '{0}'";
            StrSql.AppendFormat(sql, billingentityID);
            List<UserBillingentityInfo> userBillingentityListInfo = new List<UserBillingentityInfo>();
            using (IDataReader reader = dataBase.ExecuteReader(tran, CommandType.Text, StrSql.ToString()))
            {
                UserBillingentityInfo userBillingentityInfo = null;
                while (reader.Read())
                {
                    DateTime CS00001;
                    userBillingentityInfo = new UserBillingentityInfo((reader["ROWID"].ToString() != "") ? int.Parse(reader["ROWID"].ToString()) : 0, reader["USER_ID"].ToString(), reader["BILLINGENTITY_ID"].ToString(), reader["IS_DEFAULT"].ToString(), (byte[]) reader["TS"], reader["CREATED_BY"].ToString(), (reader["CREATED_DATE"].ToString() != "") ? DateTime.Parse(reader["CREATED_DATE"].ToString()) : (CS00001 = new DateTime()), reader["UPDATED_BY"].ToString(), (reader["UPDATED_DATE"].ToString() != "") ? DateTime.Parse(reader["UPDATED_DATE"].ToString()) : (CS00001 = new DateTime()));
                    userBillingentityListInfo.Add(userBillingentityInfo);
                }
            }
            return userBillingentityListInfo;
        }

        public int InsertUserBillingentity(UserBillingentityInfo userBillingentityInfo, string whLoginID)
        {
            int result = 0;
            DataBase db = new DataBase();
            DbConnection conn = db.connection;
            conn.Open();
            DbTransaction tran = conn.BeginTransaction();
            try
            {
                SqlParameter[] paras = this.Set_UserBillingentity_Parameters(userBillingentityInfo);
                if (paras != null)
                {
                    result += db.ExecuteNonQuery(tran, CommandType.Text, this.SQL_INSERT_USER_BILLINGENTITY.Replace("@_@", whLoginID), paras);
                }
                tran.Commit();
            }
            catch (SqlException sqlEx)
            {
                tran.Rollback();
                CommonErrorHandler.ErrorHandler(sqlEx, LogType.Error);
            }
            finally
            {
                conn.Close();
            }
            return result;
        }

        public int InsertUserBillingentity(DataBase dataBase, DbTransaction tran, UserBillingentityInfo userBillingentityInfo, string whLoginID)
        {
            int result = 0;
            try
            {
                SqlParameter[] paras = this.Set_UserBillingentity_Parameters(userBillingentityInfo);
                if (paras != null)
                {
                    result += dataBase.ExecuteNonQuery(tran, CommandType.Text, this.SQL_INSERT_USER_BILLINGENTITY.Replace("@_@", whLoginID), paras);
                }
            }
            catch (SqlException sqlEx)
            {
                CommonErrorHandler.ErrorHandler(sqlEx, LogType.Error);
            }
            return result;
        }

        public int InsertUserBillingentityByBillingentityID(DataBase dataBase, DbTransaction tran, List<UserBillingentityInfo> userBillingentityListInfo, string whLoginID)
        {
            int result = 0;
            try
            {
                foreach (UserBillingentityInfo userBillingentityInfo in userBillingentityListInfo)
                {
                    SqlParameter[] paras = this.Set_UserBillingentity_Parameters(userBillingentityInfo);
                    if (paras != null)
                    {
                        result += dataBase.ExecuteNonQuery(tran, CommandType.Text, this.SQL_INSERT_USER_BILLINGENTITY.Replace("@_@", whLoginID), paras);
                    }
                }
            }
            catch (SqlException sqlEx)
            {
                CommonErrorHandler.ErrorHandler(sqlEx, LogType.Error);
            }
            return result;
        }

        private SqlParameter[] Set_UserBillingentity_Parameters(UserBillingentityInfo userBillingentityInfo)
        {
            SqlParameter[] paramArray = new SqlParameter[] { new SqlParameter(this.USER_ID, SqlDbType.VarChar, 20), new SqlParameter(this.BILLINGENTITY_ID, SqlDbType.VarChar, 20), new SqlParameter(this.IS_DEFAULT, SqlDbType.VarChar, 1), new SqlParameter(this.CREATED_BY, SqlDbType.VarChar, 20), new SqlParameter(this.UPDATED_BY, SqlDbType.VarChar, 20) };
            paramArray[0].Value = userBillingentityInfo.UserID;
            paramArray[1].Value = userBillingentityInfo.BillingentityID;
            if (!string.IsNullOrEmpty(userBillingentityInfo.IsDefault))
            {
                paramArray[2].Value = userBillingentityInfo.IsDefault;
            }
            else
            {
                paramArray[2].Value = DBNull.Value;
            }
            paramArray[3].Value = userBillingentityInfo.CreatedBy;
            paramArray[4].Value = userBillingentityInfo.UpdatedBy;
            return paramArray;
        }

        public int UpdateUserBillingentity(UserBillingentityInfo userBillingentityInfo, string whLoginID)
        {
            int result = 0;
            DataBase db = new DataBase();
            DbConnection conn = db.connection;
            conn.Open();
            DbTransaction tran = conn.BeginTransaction();
            try
            {
                SqlParameter[] paras = this.Set_UserBillingentity_Parameters(userBillingentityInfo);
                if (paras != null)
                {
                    result += db.ExecuteNonQuery(tran, CommandType.Text, this.SQL_UPDATE_USER_BILLINGENTITY.Replace("@_@", whLoginID), paras);
                }
                tran.Commit();
            }
            catch (SqlException sqlEx)
            {
                tran.Rollback();
                CommonErrorHandler.ErrorHandler(sqlEx, LogType.Error);
            }
            finally
            {
                conn.Close();
            }
            return result;
        }

        public int UpdateUserBillingentity(DataBase dataBase, DbTransaction tran, UserBillingentityInfo userBillingentityInfo, string whLoginID)
        {
            int result = 0;
            try
            {
                SqlParameter[] paras = this.Set_UserBillingentity_Parameters(userBillingentityInfo);
                if (paras != null)
                {
                    result += dataBase.ExecuteNonQuery(tran, CommandType.Text, this.SQL_UPDATE_USER_BILLINGENTITY.Replace("@_@", whLoginID), paras);
                }
            }
            catch (SqlException sqlEx)
            {
                CommonErrorHandler.ErrorHandler(sqlEx, LogType.Error);
            }
            return result;
        }
    }
}

